package com.iqiyi.pps.epg.web.utils;


import com.alibaba.fastjson.JSONObject;
import com.iqiyi.kiwi.utils.HttpClientConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author fangying
 * @version 11-12-2 - 上午10:10
 */
public class IpUtils {

    private static final Logger log = LoggerFactory.getLogger(IpUtils.class);

    public static Integer getCountry(String ip){
        Integer countryId = null;
        try{
            StringBuilder url = new StringBuilder("http://iplocation.geo.qiyi.com/cityjson?");
            url.append("ip=").append(ip);
            HttpClientConnection connection = new HttpClientConnection(url.toString(), HttpClientConnection.GET_METHOD);
            connection.connect();
            String json = connection.getBody();
            if(json!=null && json.length()>0 && json.indexOf("=")>0){
                json = json.substring(json.indexOf("=")+1);
                json = json.substring(0,json.length()-1).trim();
                JSONObject jb= JSONObject.parseObject(json);
                JSONObject data = (JSONObject)jb.get("data");
                countryId = (Integer)data.get("country_id");
            }
        }catch (Exception e){
            log.error("[module:common] [action:getCountry]",e);
        }
        return countryId;
    }

    /**
     * 判断IP是否是中国
     * @param ip ＩＰ地址
     * @return true OR false
     */
    public static boolean isChina(String ip){
        Integer countryId = getCountry(ip);
        if(countryId==null || countryId.equals(145)){ //中国
            return true;
        }
        return false;
    }

}
